package cloudspace.vm.io.console;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;

import cloudspace.vm.VM;
import cloudspace.vm.VM.PrinterType;

/**
 * An enhanced version of {@link PrintStream} that multiplexes output to proper
 * stream handlers for individual threads.
 * 
 * @author Stephen Edwards, modified by Michael Woods
 */
public class SystemStreamMultiplexer extends PrintStream
{
	// ~ Instance/static variables
	// .............................................

	// ~ Constructors
	// ..........................................................

	private PrinterType streamID;

	// ----------------------------------------------------------
	/**
	 * Create a new print stream. This stream will not flush automatically.
	 * 
	 * @param out
	 *            The output stream to which values and objects will be printed
	 * 
	 * @see java.io.PrintWriter#PrintWriter(java.io.OutputStream)
	 */
	public SystemStreamMultiplexer(OutputStream out)
	{
		super(out, true);
	}

	// ----------------------------------------------------------
	/**
	 * Create a new print stream.
	 * 
	 * @param out
	 *            The output stream to which values and objects will be printed
	 * @param autoFlush
	 *            A boolean; if true, the output buffer will be flushed whenever
	 *            a byte array is written, one of the <code>println</code>
	 *            methods is invoked, or a newline character or byte (
	 *            <code>'\n'</code>) is written
	 * 
	 * @see java.io.PrintWriter#PrintWriter(java.io.OutputStream, boolean)
	 */
	public SystemStreamMultiplexer(OutputStream out, boolean autoFlush)
	{
		super(out, autoFlush);
	}

	// ----------------------------------------------------------
	/**
	 * Create a new print stream.
	 * 
	 * @param out
	 *            The output stream to which values and objects will be printed
	 * @param autoFlush
	 *            A boolean; if true, the output buffer will be flushed whenever
	 *            a byte array is written, one of the <code>println</code>
	 *            methods is invoked, or a newline character or byte (
	 *            <code>'\n'</code>) is written
	 * @param encoding
	 *            The name of a supported <a
	 *            href="../lang/package-summary.html#charenc"> character
	 *            encoding</a>
	 * 
	 * @exception UnsupportedEncodingException
	 *                If the named encoding is not supported
	 */
	public SystemStreamMultiplexer(OutputStream out, boolean autoFlush,
			String encoding) throws UnsupportedEncodingException
	{
		super(out, autoFlush, encoding);
	}

	// ----------------------------------------------------------
	/**
	 * Creates a new print stream, without automatic line flushing, with the
	 * specified file name. This convenience constructor creates the necessary
	 * intermediate {@link java.io.OutputStreamWriter OutputStreamWriter}, which
	 * will encode characters using the
	 * {@linkplain java.nio.charset.Charset#defaultCharset default charset} for
	 * this instance of the Java virtual machine.
	 * 
	 * @param fileName
	 *            The name of the file to use as the destination of this print
	 *            stream. If the file exists, then it will be truncated to zero
	 *            size; otherwise, a new file will be created. The output will
	 *            be written to the file and is buffered.
	 * 
	 * @throws FileNotFoundException
	 *             If the given file object does not denote an existing,
	 *             writable regular file and a new regular file of that name
	 *             cannot be created, or if some other error occurs while
	 *             opening or creating the file
	 * 
	 * @throws SecurityException
	 *             If a security manager is present and
	 *             {@link SecurityManager#checkWrite checkWrite(fileName)}
	 *             denies write access to the file
	 * 
	 * @since 1.5
	 */
	public SystemStreamMultiplexer(String fileName)
			throws FileNotFoundException
	{
		super(fileName);
	}

	// ----------------------------------------------------------
	/**
	 * Creates a new print stream, without automatic line flushing, with the
	 * specified file name and charset. This convenience constructor creates the
	 * necessary intermediate {@link java.io.OutputStreamWriter
	 * OutputStreamWriter}, which will encode characters using the provided
	 * charset.
	 * 
	 * @param fileName
	 *            The name of the file to use as the destination of this print
	 *            stream. If the file exists, then it will be truncated to zero
	 *            size; otherwise, a new file will be created. The output will
	 *            be written to the file and is buffered.
	 * 
	 * @param csn
	 *            The name of a supported {@linkplain java.nio.charset.Charset
	 *            charset}
	 * 
	 * @throws FileNotFoundException
	 *             If the given file object does not denote an existing,
	 *             writable regular file and a new regular file of that name
	 *             cannot be created, or if some other error occurs while
	 *             opening or creating the file
	 * 
	 * @throws SecurityException
	 *             If a security manager is present and
	 *             {@link SecurityManager#checkWrite checkWrite(fileName)}
	 *             denies write access to the file
	 * 
	 * @throws UnsupportedEncodingException
	 *             If the named charset is not supported
	 * 
	 * @since 1.5
	 */
	public SystemStreamMultiplexer(String fileName, String csn)
			throws FileNotFoundException, UnsupportedEncodingException
	{
		super(fileName, csn);
	}

	// ----------------------------------------------------------
	/**
	 * Creates a new print stream, without automatic line flushing, with the
	 * specified file. This convenience constructor creates the necessary
	 * intermediate {@link java.io.OutputStreamWriter OutputStreamWriter}, which
	 * will encode characters using the
	 * {@linkplain java.nio.charset.Charset#defaultCharset default charset} for
	 * this instance of the Java virtual machine.
	 * 
	 * @param file
	 *            The file to use as the destination of this print stream. If
	 *            the file exists, then it will be truncated to zero size;
	 *            otherwise, a new file will be created. The output will be
	 *            written to the file and is buffered.
	 * 
	 * @throws FileNotFoundException
	 *             If the given file object does not denote an existing,
	 *             writable regular file and a new regular file of that name
	 *             cannot be created, or if some other error occurs while
	 *             opening or creating the file
	 * 
	 * @throws SecurityException
	 *             If a security manager is present and
	 *             {@link SecurityManager#checkWrite checkWrite(file.getPath())}
	 *             denies write access to the file
	 * 
	 * @since 1.5
	 */
	public SystemStreamMultiplexer(File file) throws FileNotFoundException
	{
		super(file);
	}

	// ----------------------------------------------------------
	/**
	 * Creates a new print stream, without automatic line flushing, with the
	 * specified file and charset. This convenience constructor creates the
	 * necessary intermediate {@link java.io.OutputStreamWriter
	 * OutputStreamWriter}, which will encode characters using the provided
	 * charset.
	 * 
	 * @param file
	 *            The file to use as the destination of this print stream. If
	 *            the file exists, then it will be truncated to zero size;
	 *            otherwise, a new file will be created. The output will be
	 *            written to the file and is buffered.
	 * 
	 * @param csn
	 *            The name of a supported {@linkplain java.nio.charset.Charset
	 *            charset}
	 * 
	 * @throws FileNotFoundException
	 *             If the given file object does not denote an existing,
	 *             writable regular file and a new regular file of that name
	 *             cannot be created, or if some other error occurs while
	 *             opening or creating the file
	 * 
	 * @throws SecurityException
	 *             If a security manager is presentand
	 *             {@link SecurityManager#checkWrite checkWrite(file.getPath())}
	 *             denies write access to the file
	 * 
	 * @throws UnsupportedEncodingException
	 *             If the named charset is not supported
	 * 
	 * @since 1.5
	 */
	public SystemStreamMultiplexer(File file, String csn)
			throws FileNotFoundException, UnsupportedEncodingException
	{
		super(file, csn);
	}

	// ~ Methods
	// ...............................................................

	// ----------------------------------------------------------
	/**
	 * Write the specified byte to this stream. If the byte is a newline and
	 * automatic flushing is enabled then the <code>flush</code> method will be
	 * invoked.
	 * 
	 * <p>
	 * Note that the byte is written as given; to write a character that will be
	 * translated according to the platform's default character encoding, use
	 * the <code>print(char)</code> or <code>println(char)</code> methods.
	 * 
	 * @param b
	 *            The byte to be written
	 * @see #print(char)
	 * @see #println(char)
	 */
	public void write(int b)
	{
		super.write(b);
		VM curVM = VM.getThreadTag();
		if (curVM != null)
		{
			PrintStream vmPrinter = curVM.getStream(streamID);

			if (vmPrinter != null)
			{
				vmPrinter.print((char) b);
			}
		}
	}

	// ----------------------------------------------------------
	/**
	 * Write <code>len</code> bytes from the specified byte array starting at
	 * offset <code>off</code> to this stream. If automatic flushing is enabled
	 * then the <code>flush</code> method will be invoked.
	 * 
	 * <p>
	 * Note that the bytes will be written as given; to write characters that
	 * will be translated according to the platform's default character
	 * encoding, use the <code>print(char)</code> or <code>println(char)</code>
	 * methods.
	 * 
	 * @param buf
	 *            A byte array
	 * @param off
	 *            Offset from which to start taking bytes
	 * @param len
	 *            Number of bytes to write
	 */
	public void write(byte buf[], int off, int len)
	{
		super.write(buf, off, len);
		VM curVM = VM.getThreadTag();
		if (curVM != null)
		{
			PrintStream vmPrinter = VM.getThreadTag().getStream(streamID);
			for (int i = off; i < len; i++)
				vmPrinter.write((char) buf[i]);

		}
	}

	// ----------------------------------------------------------
	/**
	 * Need this private helper function because the PrintStream class makes its
	 * helper private, so we can't override it. Instead, we have to redefine our
	 * own, and then re-implement all the print operations on top of it all over
	 * again! Argh!
	 * 
	 * @param s
	 *            The string to write
	 */
	private void write(char buf[])
	{
		super.print(buf);
		VM curVM = VM.getThreadTag();
		if (curVM != null)
		{
			PrintStream vmPrinter = curVM.getStream(streamID);
			if (vmPrinter != null)
			{
				for (char c : buf)
					vmPrinter.print(String.valueOf(c));
			}
		}

	}

	// ----------------------------------------------------------
	/**
	 * Send all strings through the superclass print method.
	 * 
	 * @param s
	 *            The string to write
	 */
	private void write(String s)
	{
		super.print(s);
	}

	// ----------------------------------------------------------
	/**
	 * Send all newlines through the superclass println method.
	 */
	private void newLine()
	{
		super.println();
	}

	// ----------------------------------------------------------
	/**
	 * Print a boolean value. The string produced by <code>{@link
	    * java.lang.String#valueOf(boolean)}</code>
	 * is translated into bytes according to the platform's default character
	 * encoding, and these bytes are written in exactly the manner of the
	 * <code>{@link #write(int)}</code> method.
	 * 
	 * @param b
	 *            The <code>boolean</code> to be printed
	 */
	public void print(boolean b)
	{
		String output = b ? "true" : "false";
		write(output);
	}

	// ----------------------------------------------------------
	/**
	 * Print a character. The character is translated into one or more bytes
	 * according to the platform's default character encoding, and these bytes
	 * are written in exactly the manner of the <code>{@link #write(int)}</code>
	 * method.
	 * 
	 * @param c
	 *            The <code>char</code> to be printed
	 */
	public void print(char c)
	{
		String s = String.valueOf(c);
		write(s);
	}

	// ----------------------------------------------------------
	/**
	 * Print an integer. The string produced by <code>{@link
	    * java.lang.String#valueOf(int)}</code>
	 * is translated into bytes according to the platform's default character
	 * encoding, and these bytes are written in exactly the manner of the
	 * <code>{@link #write(int)}</code> method.
	 * 
	 * @param i
	 *            The <code>int</code> to be printed
	 * @see java.lang.Integer#toString(int)
	 */
	public void print(int i)
	{
		String s = String.valueOf(i);
		print(s);
	}

	// ----------------------------------------------------------
	/**
	 * Print a long integer. The string produced by <code>{@link
	    * java.lang.String#valueOf(long)}</code>
	 * is translated into bytes according to the platform's default character
	 * encoding, and these bytes are written in exactly the manner of the
	 * <code>{@link #write(int)}</code> method.
	 * 
	 * @param l
	 *            The <code>long</code> to be printed
	 * @see java.lang.Long#toString(long)
	 */
	public void print(long l)
	{
		String s = String.valueOf(l);
		write(s);
	}

	// ----------------------------------------------------------
	/**
	 * Print a floating-point number. The string produced by <code>{@link
	    * java.lang.String#valueOf(float)}</code>
	 * is translated into bytes according to the platform's default character
	 * encoding, and these bytes are written in exactly the manner of the
	 * <code>{@link #write(int)}</code> method.
	 * 
	 * @param f
	 *            The <code>float</code> to be printed
	 * @see java.lang.Float#toString(float)
	 */
	public void print(float f)
	{
		String s = String.valueOf(f);
		write(s);
	}

	// ----------------------------------------------------------
	/**
	 * Print a double-precision floating-point number. The string produced by
	 * <code>{@link java.lang.String#valueOf(double)}</code> is translated into
	 * bytes according to the platform's default character encoding, and these
	 * bytes are written in exactly the manner of the <code>{@link
	    * #write(int)}</code>
	 * method.
	 * 
	 * @param d
	 *            The <code>double</code> to be printed
	 * @see java.lang.Double#toString(double)
	 */
	public void print(double d)
	{
		String s = String.valueOf(d);
		write(s);
	}

	// ----------------------------------------------------------
	/**
	 * Print an array of characters. The characters are converted into bytes
	 * according to the platform's default character encoding, and these bytes
	 * are written in exactly the manner of the <code>{@link #write(int)}</code>
	 * method.
	 * 
	 * @param s
	 *            The array of chars to be printed
	 * 
	 * @throws NullPointerException
	 *             If <code>s</code> is <code>null</code>
	 */
	public void print(char s[])
	{
		write(s);
	}

	// ----------------------------------------------------------
	/**
	 * Print a string. If the argument is <code>null</code> then the string
	 * <code>"null"</code> is printed. Otherwise, the string's characters are
	 * converted into bytes according to the platform's default character
	 * encoding, and these bytes are written in exactly the manner of the
	 * <code>{@link #write(int)}</code> method.
	 * 
	 * @param s
	 *            The <code>String</code> to be printed
	 */
	public void print(String s)
	{
		if (s == null)
		{
			s = "null";
		}
		write(s);
	}

	// ----------------------------------------------------------
	/**
	 * Print an object. The string produced by the <code>{@link
	    * java.lang.String#valueOf(Object)}</code>
	 * method is translated into bytes according to the platform's default
	 * character encoding, and these bytes are written in exactly the manner of
	 * the <code>{@link #write(int)}</code> method.
	 * 
	 * @param obj
	 *            The <code>Object</code> to be printed
	 * @see java.lang.Object#toString()
	 */
	public void print(Object obj)
	{
		String s = String.valueOf(obj);
		write(s);
	}

	// ----------------------------------------------------------
	/**
	 * Terminate the current line by writing the line separator string. The line
	 * separator string is defined by the system property
	 * <code>line.separator</code>, and is not necessarily a single newline
	 * character (<code>'\n'</code>).
	 */
	public void println()
	{
		newLine();
	}

	// ----------------------------------------------------------
	/**
	 * Print a boolean and then terminate the line. This method behaves as
	 * though it invokes <code>{@link #print(boolean)}</code> and then
	 * <code>{@link #println()}</code>.
	 * 
	 * @param x
	 *            The <code>boolean</code> to be printed
	 */
	public void println(boolean x)
	{
		print(x);
		newLine();
	}

	// ----------------------------------------------------------
	/**
	 * Print a character and then terminate the line. This method behaves as
	 * though it invokes <code>{@link #print(char)}</code> and then
	 * <code>{@link #println()}</code>.
	 * 
	 * @param x
	 *            The <code>char</code> to be printed.
	 */
	public void println(char x)
	{

		print(x);
		newLine();

	}

	// ----------------------------------------------------------
	/**
	 * Print an integer and then terminate the line. This method behaves as
	 * though it invokes <code>{@link #print(int)}</code> and then
	 * <code>{@link #println()}</code>.
	 * 
	 * @param x
	 *            The <code>int</code> to be printed.
	 */
	public void println(int x)
	{

		print(x);
		newLine();

	}

	// ----------------------------------------------------------
	/**
	 * Print a long and then terminate the line. This method behaves as though
	 * it invokes <code>{@link #print(long)}</code> and then
	 * <code>{@link #println()}</code>.
	 * 
	 * @param x
	 *            a The <code>long</code> to be printed.
	 */
	public void println(long x)
	{

		print(x);
		newLine();
	}

	// ----------------------------------------------------------
	/**
	 * Print a float and then terminate the line. This method behaves as though
	 * it invokes <code>{@link #print(float)}</code> and then
	 * <code>{@link #println()}</code>.
	 * 
	 * @param x
	 *            The <code>float</code> to be printed.
	 */
	public void println(float x)
	{
		print(x);
		newLine();

	}

	// ----------------------------------------------------------
	/**
	 * Print a double and then terminate the line. This method behaves as though
	 * it invokes <code>{@link #print(double)}</code> and then
	 * <code>{@link #println()}</code>.
	 * 
	 * @param x
	 *            The <code>double</code> to be printed.
	 */
	public void println(double x)
	{

		print(x);
		newLine();

	}

	// ----------------------------------------------------------
	/**
	 * Print an array of characters and then terminate the line. This method
	 * behaves as though it invokes <code>{@link #print(char[])}</code> and then
	 * <code>{@link #println()}</code>.
	 * 
	 * @param x
	 *            an array of chars to print.
	 */
	public void println(char x[])
	{

		print(x);
		newLine();

	}

	// ----------------------------------------------------------
	/**
	 * Print a String and then terminate the line. This method behaves as though
	 * it invokes <code>{@link #print(String)}</code> and then
	 * <code>{@link #println()}</code>.
	 * 
	 * @param x
	 *            The <code>String</code> to be printed.
	 */
	public void println(String x)
	{

		print(x);
		newLine();

	}

	// ----------------------------------------------------------
	/**
	 * Print an Object and then terminate the line. This method behaves as
	 * though it invokes <code>{@link #print(Object)}</code> and then
	 * <code>{@link #println()}</code>.
	 * 
	 * @param x
	 *            The <code>Object</code> to be printed.
	 */
	public void println(Object x)
	{

		print(x);
		newLine();

	}

	// ----------------------------------------------------------
	/**
	 * Appends a subsequence of the specified character sequence to this output
	 * stream.
	 * 
	 * <p>
	 * An invocation of this method of the form <tt>out.append(csq, start,
	 * end)</tt> when <tt>csq</tt> is not <tt>null</tt>, behaves in exactly the
	 * same way as the invocation
	 * 
	 * <pre>
	 * out.print(csq.subSequence(start, end).toString())
	 * </pre>
	 * 
	 * @param csq
	 *            The character sequence from which a subsequence will be
	 *            appended. If <tt>csq</tt> is <tt>null</tt>, then characters
	 *            will be appended as if <tt>csq</tt> contained the four
	 *            characters <tt>"null"</tt>.
	 * 
	 * @param start
	 *            The index of the first character in the subsequence
	 * 
	 * @param end
	 *            The index of the character following the last character in the
	 *            subsequence
	 * 
	 * @return This character stream
	 * 
	 * @throws IndexOutOfBoundsException
	 *             If <tt>start</tt> or <tt>end</tt> are negative,
	 *             <tt>start</tt> is greater than <tt>end</tt>, or <tt>end</tt>
	 *             is greater than <tt>csq.length()</tt>
	 * 
	 * @since 1.5
	 */
	public PrintStream append(CharSequence csq, int start, int end)
	{
		CharSequence cs = (csq == null ? "null" : csq);
		String subseq = cs.subSequence(start, end).toString();
		/*
		 * PrintStream vmPrinter = VM.getThreadTag().getStream( streamID); if
		 * (vmPrinter != null) { vmPrinter.print(subseq); }
		 */
		write(subseq);
		return this;
	}

	public void setStream(PrinterType type)
	{
		streamID = type;

	}
}